<template>
	<view>
		<up-popup :show="show" mode="bottom" :round="10" @close="handleClose">
			<view>
				<view class="picker-btn">
					<view class="cancel btn" @click="handleClose">取消</view>
					<view class="confirm btn" @click="handleConfirm">确认</view>
				</view>
				<picker-view :value="pickerValue" @change="bindChange" class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in firstGradeData" :key="index">
							{{ keyName?item[keyName] : item }}
						</view>
					</picker-view-column>
					<picker-view-column v-if="type == 2">
						<view class="item" v-for="(item,index) in secondGradeData" :key="index">
							{{ keyName?item[keyName] : item }}
						</view>
					</picker-view-column>
				</picker-view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import { ref, watch } from 'vue'
	const props = defineProps({
		show:{
			type: Boolean,
			default: false
		},
		datas:{
			type:Array,
			defalut:()=>{
				return []
			}
		},
		keyName:{
			type:String,
			defalut:()=>{
				return ''
			}
		},
		// 1一级（选择） 2 二级（选择）
		type: {
			type: [Number,String],
			default: 1
		},
	})
	const emit = defineEmits(['update:show','close','confirm'])
	
	const showPopup = ref(false)
	const pickerValue = ref([0])
	// 一级数据
	const firstGradeData = ref([])
	// 二级数据
	const secondGradeData = ref([])
	
	// 初始化数据
	const initPicker = ()=>{
		firstGradeData.value = props.datas
		// 二级
		if(props.type == 2){
			pickerValue.value = [0,0]
			secondGradeData.value = props.datas[pickerValue.value[0]].children
		}
	}
	
	
	const bindChange = (e)=>{
		console.log(e)
		pickerValue.value = e.detail.value
		// 二级
		if(props.type == 2){
			secondGradeData.value = props.datas[pickerValue.value[0]].children
		}
	}
	
	const handleClose = ()=>{
		emit('update:show',false)
		emit('close')
	}
	const handleConfirm = ()=>{
		if(props.type == 1){
			emit('confirm',firstGradeData.value[pickerValue.value[0]])
		}else if(props.type == 2){
			emit('confirm',secondGradeData.value[pickerValue.value[1]])
		}
		handleClose()
	}
	
	watch(()=>props.show,(val)=>{
		showPopup.value = val
		if(val){
			// 延迟初始化确保DOM渲染完成
			setTimeout(initPicker, 50)
		}
	})
</script>

<style lang="scss">
	.picker-view {
		width: 750rpx;
		height: 600rpx;
		margin-top: 20rpx;
	}
	.item {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 50px;
		font-size: 34rpx;
		color: #333;
	}
	.picker-btn{
		display: flex;
		justify-content: space-between;
		.btn{
			padding: 30rpx;
			font-size: 32rpx;
		}
		.cancel{
			color: #CCCCCC;
		}
		.confirm{
			color: #F5564D;
		}
	}
</style>